/* eslint-disable react/react-in-jsx-scope */
import { history } from 'umi';
import { accountLogin, getCodeImg ,getUserInfo,queryUserRole,checkToken} from '@/services/login';
import { message } from 'antd/lib/index';
import Cookie from '../utils/cookie';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    codeImgInfo: {
      uuid: '',
      captcha: ''
    },
    user: {},
    authList:[],
  },

  effects: {
    *getAuthData({ payload }, { call, put }) {
      const userId = Cookie.get('userName');
      const authArr = [
        {
          "label": "维度管理",
          "value": "dimensionManagement"
        },
        {
          "label": "维值管理",
          "value": "dimensionValueManagement"
        },
        {
          "label": "基础指标管理",
          "value": "basicIndexManagement"
        },
        {
          "label": "指标管理",
          "value": "indexManagement"
        },
        {
          "label": "用户管理",
          "value": "userManage"
        },
        {
          "label": "角色管理",
          "value": "roleManage"
        },
        {
          "label": "指标知识图谱",
          "value": "indexMapManagement"
        },
        {
          "label": "用户明细",
          "value": "userDetail"
        },
      ]
      if(userId==="admin"||userId==="test_admin"){
        localStorage.setItem("authList",JSON.stringify(authArr))
        return    yield put({
          type: 'updateState',
          payload: {
            authList: authArr
          }
        })
      }
      const res = yield call(queryUserRole,payload)
      if (res && (res?.code === 200 || res?.code === 0)) {
        if (res?.result?.length > 0) {
          let arr = res.result.map((item) => JSON.parse(item));
          let arr1 = [];
          let arr2 = [];
          arr.forEach((item) => {
            arr1 = arr1.concat(item);
          });
          arr1.forEach((item) => {
            if (!arr2.some((item1) => item1.value === item.value)) {
              arr2.push(item);
            }
          });
          localStorage.setItem("authList",JSON.stringify(arr2))
          yield put({
            type: 'updateState',
             payload: {
               authList: arr2
             }
          })
        }
      } else {
        localStorage.removeItem("authList");
        yield put({
          type: 'updateState',
          payload: {
            authList: []
          }
        })
      }
    },
    *getAuthList({ callback }, { call, put }) {
       const res = yield call(getUserInfo)
      if (res && res.code === 200) {
        let selectedroles = res?.result?.userInfo?.selectedroles || "";
        if (selectedroles) {
          yield put({
            type: 'getAuthData',
            payload:{ roleId: selectedroles }
          })
        }
        if(Cookie.get('userId')) Cookie.del('userId');
        Cookie.set('userId', res?.result?.userInfo?.id);
        yield put({
          type: 'intellectAssistant/updateState',
          payload: {
            userId: res?.result?.userInfo?.id,
          }
        });
        if(callback) callback()
      }else {
        yield put({
          type: 'updateState',
          payload: {
            authList: []
          }
        })
        if(Cookie.get('userId')) Cookie.del('userId');
        yield put({
          type: 'intellectAssistant/updateState',
          payload: {
            userId: "",
          }
        });
      }
    },
    *login({ payload, callback }, { call, put }) {
      const response = yield call(accountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      if (response?.code === 200) {
        if (callback) callback(response);
      }else{
        message.error(response.message,4);
        yield put({
          type: 'getCaptchaImage',
        });
      }
    },
    *checkToken({ payload, callback }, { call, put }) {
      const response = yield call(checkToken, payload);
      if (response?.code === 200) {
        yield put({
          type: 'changeLoginStatus',
          payload: response,
        });
        if (callback) callback(response);
      }else {
        message.info(response?.message||response?.data)
      }
    },

    *getCaptchaImage({ payload, callback }, { call, put }) {
      const response = yield call(getCodeImg)
      if (response?.code === 200) {
        yield put({
          type: 'setCaptchaImage',
          payload: response.data,
        })
        if (callback) callback(response.data)
      }
    },

    // eslint-disable-next-line require-yield
    *logout({},{put}) {
      const currentUser = Cookie.get('userName'); // 拿到当前存在Cookie中的username（取自登录接口的应答报文）
      Cookie.del('token', '/');
      Cookie.del('userId', '/');
      Cookie.del('count', '/');
      Cookie.del('JSESSIONID', '/');
      Cookie.del('CASTGC', '/');
      Cookie.del('loginId', '/');
      Cookie.del('userName', '/');
      localStorage.removeItem("authList");
      message.success(`用户已成功登出`); // 把用户名放入登出信息之中
      // 先弹出登出的消息，随后页面跳转回登录页面
      yield put({
        type: 'intellectAssistant/updateState',
        payload: {
          messageList: [],
          indexPredictData:{}, //预查询弹窗数据
          dialogueList: {}, // 历史会话列表
          dialogueOneInfo: [], // 点击历史会话的某一条
          dialogueId:"",//会话id
          dialogueIdGz:"",//会话id
          dialogueIdAI:"",//会话id
          title:"新会话",//会话名称
          titleGz:"新会话",
          titleAI:"新会话",
          top5List:[],
          isLoading:false,
          managementName:"维度管理",
          hotQuestion:[],
          dialogFlag:"0",//页签id
          backMessageListGz:[],//规则取数备份数据
          backMessageListAI:[],//AI取数备份数据
          userId:"",
          pageContent:[],//参考资料
          checkedSwitch:false,
          pageFileList:[],//文件列表
          tenantId:"", //权限标识
        }
      });
      history.replace({
        pathname: '/login',
      });
    },
  },

  reducers: {
    login(state, { payload ,callback}) {
      if(callback) callback()
      return {
        ...state,
        ...payload
      };
    },
    changeLoginStatus(state, { payload }) {
      return {
        ...state,
        user: payload,
      };
    },
    setCaptchaImage(state, { payload }){
      return {
        ...state,
        codeImgInfo: payload,
      };
    },
  },
};
